<?php

namespace addons\kuerp\controller;

use addons\kuerp\model\ExamineRecord;
use addons\kuerp\model\FormField;
use addons\kuerp\model\Message;
use addons\kuerp\model\Collection as ReceivablesModel;
use addons\kuerp\model\ReceivablesOther;
use addons\kuerp\model\Contract;
use addons\kuerp\model\Staff;
use addons\kuerp\model\GoodsSales;
use think\Db;
use think\Exception;
/**
 * 回款详情
 */
class Collection extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];

    public function _initialize()
    {
        parent::_initialize();
    }

	//新增回款
	public function addReceivables() {
		$params = $this->request->post();
		// 表单验证
		if (($result = $this->kuerpValidate($params,get_class(), 'create')) !== true) {
			$this->error($result);
		}
		if (ReceivablesModel::where(['number' => $params['number'], 'contract_id' => $params['contract_id']])->find()) {
			$this->error('回款编号已存在');
		}
		$contract=Contract::where(['id'=>$params['contract_id']])->find();
		if(empty($contract)){
			$this->error('合同不存在');
		}
		if($contract['check_status'] != 2){
			$this->error('当前合同未审核通过');
		}
		$returnWhere['check_status'] = ['in',[0,1,2]];
		$returnWhere['contract_id'] = $params['contract_id'];
		$returnMoeny = ReceivablesModel::where($returnWhere)->sum('money');
		if($returnMoeny >= $contract['money']){
            $this->error('当前合同已回款完毕');
        }
        if($returnMoeny + $params['money'] > $contract['money']){
        //    $this->error('回款累计总金额已超过合同金额');
        }

        $result = FormField::checkFields(FormField::RECEIVABLES_TYPE,$params);
        if ($result !== true) {
            $this->error($result);
        }
		Db::startTrans();
		try {
		    $params['customer_id']=$contract['customer_id'];
			ReceivablesModel::createReceivables($params);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		if ($result) {
			$this->success('新增回款成功');
		}
	}


	//获取回款列表
	public function getList() {

        $params = $this->request->post();
		$customer_id          = input('customer_id');
		$contract_id          = input('contract_id');
		$purchase_code          = input('purchase_code');
		$check_status         = input('check_status');
		$name         = input('name');
        $staff_id=input('staff_id');
        $createtime=input('createtime');

		$limit                = input('limit');
		$where                = [];
        //审核状态 1审核中、2审核通过、3审核未通过
        if(isset($check_status)){
			$where['examine_status']=$check_status;
            //0待审核、1审核中、2审核通过、3审核未通过、4撤销
            // if($check_status == 1){
            //     $where['check_status']=['in',[0,1]];
            // }elseif($check_status == 2){
            //     $where['check_status']=2;
            // }elseif($check_status == 3){
            //     $where['check_status']=3;
            // }
        }
		if($customer_id){
			$where['customers_id'] = $customer_id;
		}
		if($name){
			$where['collection.purchase_code|customer.customer_name|staffmember.name'] = ['like',"%{$name}%"];
		}
		if($contract_id){
			// $where['contract_id'] = $contract_id;
			//获取单号
			$order_code = GoodsSales::where(['id'=>$contract_id])->value('purchase_code');
			$where['collectionsale.purchase_number'] = $order_code;
			$where['collectionsale.business_type'] = 3;
		}
        if($purchase_code){
             $where['collectionsale.purchase_number'] = $purchase_code;
        }
		if($staff_id){
			$where['collection.staff_member_id'] = $staff_id;
		}else{
            $where['collection.staff_member_id'] = ['exp', Db::raw(' in ('.implode(',', $this->auth->sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];//['in', $this->auth->sale_users];
            if (isset($params['type']) && $params['type']) {//客户分类
                if ($params['type'] == 1) {//我的创建
                    $where['collection.staff_member_id'] = $this->auth->staff_member_id;
                } elseif ($params['type'] == 2) {//下属创建
					$sale_users = $this->auth->sale_users;
					if (in_array($this->auth->staff_member_id, $sale_users)) {
						$sale_users = array_diff($sale_users, [$this->auth->staff_member_id]);
					}
                    $where['collection.staff_member_id'] = ['in', $sale_users];
                }
            }
        }
		if($createtime){
            $times = setTimes($createtime, 'time');
            $where['collection.createtime'] = ['between', $times];
		}
        if (isset($params['times']) && $params['times']) {//客户分类

            $times = setTimes($params['times'], 'time');
            $where['collection.purchase_time'] = ['between', $times];
        }
        if(isset($params['id_list'])){//日志 查询id列表
            $where=[];
            $where['collection.id']=['in',explode(',',$params['id_list'])];
        }

		$list = ReceivablesModel::where($where)->with(['collectionsale','customer','staffmember'])->order('collection.id desc')->paginate($limit);
		foreach ($list as $row) {
			$row->getRelation('collectionsale')->visible(['purchase_number']);
			$row->getRelation('customer')->visible(['customer_name']);
			$row->getRelation('staffmember')->visible(['name']);
		}
		$list = $list->toArray();
        $data = $list['data'];
        $moneyinfo= [
			'allmoney' => 0,
			'nomoney' => 0,
		];
		//获取id
		if ($data) {
			$codes = array_column(array_column($data,'collectionsale'), 'purchase_number');
			$orders = GoodsSales::where(['purchase_code'=>['in', $codes]])->field('sum(real_money) as allmoney, sum(real_money - pay_money) as unback_money')->find();
			$moneyinfo['allmoney'] = round($orders['allmoney'] ?? 0, 2);//GoodsSales::where(['purchase_code'=>['in', $codes]])->sum('real_money');
			$moneyinfo['nomoney'] = round($orders['unback_money'] ?? 0, 2);//GoodsSales::where(['purchase_code'=>['in', $codes]])->sum('real_money');
			foreach ($list['data'] as $key => $value) {
				$list['data'][$key]['customers'] = $value['customer'];
				$list['data'][$key]['staff'] = $value['staffmember'];
				unset($list['data'][$key]['customer'],$list['data'][$key]['staffmember']);
			}
		}
        $where['examine_status']=1;
        $remoney = ReceivablesModel::where($where)->with(['collectionsale','customer','staffmember'])->sum('collection.money');
        $where['examine_status']=array('in','0,1');
        $inmoney = 0;//ReceivablesModel::where($where)->sum('money');
        $where['examine_status']=array('in','3,4');
        $nomoney = 0;//ReceivablesModel::where($where)->sum('money');
        $moneyinfo['remoney'] = $remoney;//已回款
        $moneyinfo['inmoney'] = $inmoney;//回款中
        // $moneyinfo['nomoney'] = $moneyinfo['allmoney'] - $nomoney;//未回款
        // $moneyinfo['allmoney'] = GoodsSales::where(['id'=>['in',$contractId]])->sum('real_money');//总金额
        $list['moneyinfo']=$moneyinfo;
		$this->success('请求成功', $list);
	}


	//回款详情
	public function getDetail() {
		$id       = input('id');
		$receivables = ReceivablesModel::where(['collection.id' => $id])->with([
            'collectionsale','customers','staff'
		])->find();

		if (empty($receivables)) {
			$this->error('信息不存在');
		}
		$receivables=$receivables->toArray();
        $receivables['is_operation']=0;

        if($receivables['staff_member_id'] == $this->auth->staff_member_id){
            //是否可以操作
            $receivables['is_operation']=1;
        }

        if ($receivables['examine_status'] == 1){
            $receivables['is_examine'] = 1;
        } else {
            $receivables['is_examine'] = 0;
        }
        if ($receivables['examine_status'] == 0 && ($receivables['examine_index'] > 0 || ($receivables['examine_index'] == 0 && $receivables['examine_adminids'] != ''))) {
            $receivables['examine_status'] = 3;
        }
        $receivables['createtime'] = date('Y-m-d H:i', $receivables['createtime']);
        $receivables['updatetime'] = date('Y-m-d H:i', $receivables['updatetime']);
        $receivables['collection_account'] = Db::name('kuerp_collection_account')->alias('a')
            ->join('kuerp_accounts b','a.accounts_id=b.id','left')
            ->where('a.collection_id',$id)
            ->field('a.money,b.account_name')
            ->select();

//        $receivables=ReceivablesOther::getOther($receivables);
//		//标记通知已读
//		Message::setRead(Message::RECEIVABLES_TYPE, $id, $this->auth->id);
		$this->success('请求成功', $receivables);
	}


	//撤回审核
	public function cancel() {
		$id       = input('id');
		$customer = ReceivablesModel::where(['id' => $id, 'check_status' => 1])->find();
		if (empty($customer)) {
			$this->error('回款信息不存在');
		}
        if($customer['owner_staff_id'] != $this->auth->id){
            $this->error('只有负责人可以撤回审批');
        }
		Db::startTrans();
		try {

			ReceivablesModel::where(['id' => $id])->update(['check_status' => 4]);
			ExamineRecord::where([
				'relation_type' => ExamineRecord::RECEIVABLES_TYPE,
				'relation_id'   => $id,
				'status'        => 0
			])->update(['status' => 3]);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();;
			$this->error($e->getMessage());
		}


		$this->success('撤回成功');
	}


	//修改回款
	public function editReceivables() {
		$id     = input('id');
		$params = $this->request->post();
		$row    = ReceivablesModel::where(['id' => $id, 'check_status' => ['in', [3, 4]]])->find();
		if (empty($row)) {
			$this->error('回款信息不存在');
		}
		// 表单验证
		if (($result = $this->kuerpValidate($params,get_class(), 'create')) !== true) {
			$this->error($result);
		}
        $contract=Contract::where(['id'=>$row['contract_id']])->find();
        $returnWhere['check_status'] = ['in',[0,1,2]];
        $returnWhere['contract_id'] =$row['contract_id'];
        $returnMoeny = ReceivablesModel::where($returnWhere)->sum('money');
        if($returnMoeny >= $contract['money']){
            $this->error('合同已全部回款');
        }
        if($returnMoeny + $row['money'] > $contract['money']){
        //    $this->error('回款累计总金额已超过合同金额');
        }

        $result = FormField::checkFields(FormField::RECEIVABLES_TYPE,$params,$id);
        if ($result !== true) {
            $this->error($result);
        }
		Db::startTrans();
		try {
			$result = ReceivablesModel::updateReceivables($params);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		$this->success('修改回款信息成功');
	}

    //获取回款编号
    public function getReceivablesNumber() {
        $this->success('请求成功',['number'=>'H' . date('ymd') . rand(100, 999)]);
    }
}
